#include "hi_ext_util.h"
#include "plug_hisignalling.h"
#include "hisignalling.h"


#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif
#endif /* End of #ifdef __cplusplus */
static PLUG_HISIGNALLING_INFO s_stInfo = {0};
int flag = 1;
int uar_fd;
static pthread_t s_HISIGNALLINGTaskId = 0;

HI_U8 g_send_buffer[4]  = {0,2,0,1};

HI_S32 PLUG_HISIGNALLING_Init(PLUG_HISIGNALLING_INFO stInfo)
{
    HI_S32 s32Ret = HI_SUCCESS;
    // Init uart
    uar_fd = uartOpenInit();
    if(uar_fd < 0){
        LOGI("uart laod failed.");
    }
    else
    {
        LOGI("uart load successed.");
    }
    memcpy(&s_stInfo, &stInfo, sizeof(PLUG_HISIGNALLING_INFO));

    s32Ret = pthread_create(&s_HISIGNALLINGTaskId, HI_NULL, PLUG_HISIGNALLING_RecvMsg, HI_NULL);

    if (HI_SUCCESS != s32Ret)
    {
        
        LOGE("pthread create PLUG_HISIGNALLING_MSRecv failed!\n");
    }

    return HI_SUCCESS;
}
HI_S32 PLUG_HISIGNALLING_RecvMsg(HI_VOID)
{
    
    unsigned char read_buff[29] = {0};
        HI_U8 u8Msg[24] = {0};
    

    while (flag)
    {   
   
        memset(u8Msg, 0x0, sizeof(u8Msg));
        memset(read_buff, 0x0, sizeof(read_buff));
        
        uart_recevice(uar_fd,read_buff,sizeof(read_buff)/sizeof(read_buff[0]));
        

        memcpy(u8Msg, &read_buff[4], 20);
        u8Msg[20] = '\0';

        HI_S32 s32Len = 0;
        s32Len = strlen(u8Msg);

        // printf("s32Len:%d\n", s32Len);

        u8Msg[s32Len - 1] = '\0';

//         printf("%s\n", u8Msg);

        if (strlen(u8Msg) != 0)
        {
            s_stInfo.pfnRecMsg(u8Msg);
        }

    }   

    return HI_SUCCESS;
}

HI_S32 PLUG_HISIGNALLING_SendMsg(PLUG_COMMON_HISIGNALING_GESTURE_E enType)
{
     if( enType < PLUG_COMMON_GREEN_LIGHT_ON && enType >= PLUG_COMMON_BUTT)
     {
         return HI_FAILURE;
     }
     switch (enType) 
     {
         case PLUG_COMMON_GREEN_LIGHT_ON:
             g_send_buffer[3] = 0;
             break;
         case PLUG_COMMON_GREEN_LIGHT_OFF:
             g_send_buffer[3] = 1;
             break;
         default:
             printf("no match type !!!");
             break;    
     }
    
    if(s_stInfo.pfnSenMsg != HI_NULL)
    {
         s_stInfo.pfnSenMsg(uar_fd,g_send_buffer);
    }

    return HI_SUCCESS;
}

HI_S32 PLUG_HISIGNALLING_Deinit(HI_VOID)
{
    flag = 0;
    return HI_SUCCESS;
}

#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif /* End of #ifdef __cplusplus */

